package org.luxor.html.exception;

import org.luxor.commons.core.utils.HttpContextUtils;
import org.luxor.commons.core.web.RestStatus;
import org.luxor.commons.core.web.data.R;
import org.luxor.html.service.TemplateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * SpringMVC 异常处理器
 *
 * @author Mr.yan @date 2019/9/21
 */
@ConditionalOnBean({TemplateService.class})
public class CustomExceptionResolver implements HandlerExceptionResolver {
    private static final Logger logger = LoggerFactory.getLogger(CustomExceptionResolver.class);

    @Resource
    private TemplateService themeService;

    @Override
    public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
        if (logger.isErrorEnabled()) {
            logger.error("出现错误:", ex);
        }

        if (HttpContextUtils.isAjax(request)) {
            // Ajax请求过程中产生的异常处理
            HttpContextUtils.sendJson(response, new R(RestStatus.ERROR, ex.getMessage()));
            return new ModelAndView();
        } else {
            ModelAndView mv = new ModelAndView();
            mv.addObject("message", ex.getMessage());
            mv.addObject("exception", ex);

            // 普通异常的处理
            mv.setViewName(themeService.getError());
            return mv;
        }
    }
}
